<template>
  <div class="dashboard">
    <h2>数据看板</h2>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon bg-blue">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.members }}</div>
              <div class="stat-label">会员总数</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon bg-green">
              <el-icon><Collection /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.courses }}</div>
              <div class="stat-label">课程总数</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon bg-orange">
              <el-icon><Calendar /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.todayCourses }}</div>
              <div class="stat-label">今日课程</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon bg-red">
              <el-icon><UserFilled /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.coaches }}</div>
              <div class="stat-label">教练人数</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>会员增长趋势</span>
            </div>
          </template>
          <div ref="membersChart" class="chart-container"></div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>课程预约情况</span>
            </div>
          </template>
          <div ref="bookingsChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-row :gutter="20" class="tables">
      <el-col :span="12">
        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <span>热门课程排行</span>
            </div>
          </template>
          <el-table :data="popularCourses" style="width: 100%" stripe>
            <el-table-column prop="rank" label="排名" width="60" />
            <el-table-column prop="name" label="课程名称" />
            <el-table-column prop="bookings" label="预约人数" />
            <el-table-column prop="capacity" label="总容量" />
          </el-table>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <span>教练课程安排</span>
            </div>
          </template>
          <el-table :data="coachSchedule" style="width: 100%" stripe>
            <el-table-column prop="coach" label="教练" />
            <el-table-column prop="courses" label="课程数" />
            <el-table-column prop="students" label="学员数" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import * as echarts from 'echarts'
import { User, Collection, Calendar, UserFilled } from '@element-plus/icons-vue'
import api from '@/util/api'

// 统计数据
const stats = ref({
  members: 0,
  courses: 0,
  todayCourses: 0,
  coaches: 0
})

// 课程数据
const coursesData = ref([])

// 会员数据
const membersData = ref([])

// 教练数据
const coachesData = ref([])

// 热门课程数据（基于实际数据计算）
const popularCourses = computed(() => {
  if (!coursesData.value.length) return []

  // 根据预约人数排序课程
  const sortedCourses = [...coursesData.value]
      .sort((a, b) => b.bookedCount - a.bookedCount)
      .slice(0, 5)

  return sortedCourses.map((course, index) => ({
    rank: index + 1,
    name: course.name,
    bookings: course.bookedCount,
    capacity: course.maxCapacity
  }))
})

// 教练安排数据（基于实际数据计算）
const coachSchedule = computed(() => {
  if (!coursesData.value.length || !coachesData.value.length) return []

  // 创建教练映射
  const coachMap = {}
  coachesData.value.forEach(coach => {
    coachMap[coach.name] = {
      name: coach.name,
      courses: 0,
      students: 0
    }
  })

  // 统计每个教练的课程数和学员数
  coursesData.value.forEach(course => {
    if (coachMap[course.coach]) {
      coachMap[course.coach].courses += 1
      coachMap[course.coach].students += course.bookedCount
    }
  })

  // 转换为数组并排序
  return Object.keys(coachMap)
      .map(coachName => ({
        coach: coachMap[coachName].name,
        courses: coachMap[coachName].courses,
        students: coachMap[coachName].students
      }))
      .sort((a, b) => b.students - a.students)
      .slice(0, 5)
})



// 今日课程数计算
const calculateTodayCourses = () => {
  const today = new Date().toISOString().split('T')[0]
  let count = 0

  coursesData.value.forEach(course => {
    if (course.startTime && course.startTime.startsWith(today)) {
      count++
    }
  })

  stats.value.todayCourses = count
}

// 获取会员数据
const fetchMembers = async () => {
  try {
    const response = await api({
      url: '/members',
      method: 'get',
      params: {
        pageNo: 1,
        pageSize: 1000 // 获取所有会员
      }
    })
    membersData.value = response.data.records
    stats.value.members = response.data.total
  } catch (error) {
    console.error('获取会员数据失败:', error)
  }
}

// 获取课程数据
const fetchCourses = async () => {
  try {
    const response = await api({
      url: '/courses',
      method: 'get',
      params: {
        pageNo: 1,
        pageSize: 1000 // 获取所有课程
      }
    })

    coursesData.value = response.data.records
    stats.value.courses = response.data.total
    calculateTodayCourses()
  } catch (error) {
    console.error('获取课程数据失败:', error)
  }
}

// 获取教练数据
const fetchCoaches = async () => {
  try {
    const response = await api({
      url: '/coaches',
      method: 'get',
      params: {
        pageNo: 1,
        pageSize: 1000 // 获取所有教练
      }
    })

    coachesData.value = response.data.records
    stats.value.coaches = response.data.total
  } catch (error) {
    console.error('获取教练数据失败:', error)
  }
}

// 图表实例
const membersChart = ref(null)
const bookingsChart = ref(null)
let membersChartInstance = null
let bookingsChartInstance = null

// 初始化图表
const initCharts = () => {
  // 会员增长趋势图（模拟数据，实际应用中应根据会员注册日期统计）
  membersChartInstance = echarts.init(membersChart.value)
  const membersOption = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: [20, 35, 28, 42, 38, stats.value.members],
      type: 'line',
      smooth: true,
      itemStyle: { color: '#409EFF' },
      areaStyle: { color: '#409EFF', opacity: 0.3 }
    }]
  }
  membersChartInstance.setOption(membersOption)

  // 课程预约情况图
  const totalBookings = coursesData.value.reduce((sum, course) => sum + course.bookedCount, 0)
  const totalCapacity = coursesData.value.reduce((sum, course) => sum + course.maxCapacity, 0)
  const availableCapacity = totalCapacity - totalBookings

  bookingsChartInstance = echarts.init(bookingsChart.value)
  const bookingsOption = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      bottom: '0%'
    },
    series: [
      {
        name: '预约情况',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#ffffff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: totalBookings, name: '已预约' },
          { value: availableCapacity, name: '剩余容量' }
        ]
      }
    ]
  }
  bookingsChartInstance.setOption(bookingsOption)
}

// 更新图表数据
const updateCharts = () => {
  if (membersChartInstance) {
    const totalMembers = stats.value.members
    const membersOption = {
      series: [{
        data: [20, 35, 28, 42, 38, totalMembers]
      }]
    }
    membersChartInstance.setOption(membersOption)
  }

  if (bookingsChartInstance) {
    const totalBookings = coursesData.value.reduce((sum, course) => sum + course.bookedCount, 0)
    const totalCapacity = coursesData.value.reduce((sum, course) => sum + course.maxCapacity, 0)
    const availableCapacity = totalCapacity - totalBookings

    const bookingsOption = {
      series: [
        {
          data: [
            { value: totalBookings, name: '已预约' },
            { value: availableCapacity, name: '剩余容量' }
          ]
        }
      ]
    }
    bookingsChartInstance.setOption(bookingsOption)
  }
}

// 窗口大小改变时重置图表
const resizeCharts = () => {
  if (membersChartInstance) {
    membersChartInstance.resize()
  }
  if (bookingsChartInstance) {
    bookingsChartInstance.resize()
  }
}

// 加载所有数据
const loadData = async () => {
  await Promise.all([
    fetchMembers(),
    fetchCourses(),
    fetchCoaches()
  ])

  // 初始化或更新图表
  if (!membersChartInstance && !bookingsChartInstance) {
    initCharts()
  } else {
    updateCharts()
  }
}

onMounted(() => {
  loadData()
  window.addEventListener('resize', resizeCharts)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeCharts)
  if (membersChartInstance) {
    membersChartInstance.dispose()
  }
  if (bookingsChartInstance) {
    bookingsChartInstance.dispose()
  }
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.stat-icon el-icon {
  font-size: 24px;
  color: white;
}

.bg-blue {
  background-color: #409EFF;
}

.bg-green {
  background-color: #67C23A;
}

.bg-orange {
  background-color: #E6A23C;
}

.bg-red {
  background-color: #F56C6C;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.charts, .tables {
  margin-bottom: 20px;
}

.chart-card, .table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}

.chart-container {
  width: 100%;
  height: 300px;
}
</style>
